function [threshold allsacs] = findallsacs(F, tnum, ct)
% function [t sac] = findsacs_b(F, i, ct)
% threshold     = the calculated threshold
% allsacs  =   a list of starting and end points of all saccades within the given trial
%
% F     = structure with F and user data (see GUIDATA)
% tnum  = the current trial number
% ct    = a custom threshold can be used (-1 = auto find using F.MULT )
s=F.speed{tnum};
sbase=s(s<50 & ~F.blink{tnum});    % 50 deg/s is old cutoff & no blink
%sbase=s(s<50 );    % 50 deg/s is old cutoff. remove anything below that
if ct >= 0
    threshold=ct;
else
    threshold=mode(sbase)+std(sbase)*F.TMULT;
end
if ~isfield(F,'sacdurmin')
    F.sacdurmin = uint8(zeros(size(F.trials),1))+10; % min duration for saccade is 10ms. will never be more than 255ms    
end
%    clf; hold on; plot(s,'.-g');  plot(find(s>threshold),s(s>threshold),'.b'); plot(find(s>40),s(s>40),'.k');hline(threshold,'--g')
s(end)=0;
d=diff([0;s]>=threshold); % Speed goes above threshold%
e=[max(1,find(d==1)-1) find(d==-1)];
l=e(:,2)-e(:,1)-1;

allsacs=[];
n2=size(e,1);
if n2 > 0
    fsac=find(l> (F.sacdurmin(tnum)/(1000/F.res.rec_rate)) ); % Saccades must last longer than 10ms long 
    if ~isempty(fsac)
        allsacs=e(fsac,:);
    end
end
 % vline(allsacs,'b')
%speed cutoff
lalala=zeros(1,size(allsacs,1))>1;
for ii =1:size(allsacs,1)
    lalala(ii)=max(s(allsacs(ii,1):allsacs(ii,2)))<min(threshold*2,40); % twice the threshold, or 40, whichever's less
end
allsacs(lalala,:)=[];

%vline(sac(:,1),'--r');vline(sac(:,2),'--k')